import { debounce } from 'lodash'
import { onBeforeMount, onBeforeUnmount } from 'vue'
import useAppStore from '@/store/modules/app.js'
import useBlogStore from '@/store/modules/blog.js'

const { body } = document

export function resizeHandler() {
  const WIDTH = 992 // refer to Bootstrap's responsive design
  const BLOG_MENU_WIDTH = 800 // bolg menu width
  const BLOG_MAIN_WIDTH = 1080 // blog main view width
  const appStore = useAppStore()
  const blogStore = useBlogStore()
  const resizeHandler = () => {
    const rect = body.getBoundingClientRect()
    if (rect.width - 1 < WIDTH) {
      appStore.setMachineType('mobile')
      // 关闭侧边栏
      appStore.closeCollapse()
    }
    else {
      appStore.setMachineType('desktop')
      // 打开侧边栏
      appStore.openCollapse()
    }
    if (rect.width + 1 > BLOG_MAIN_WIDTH) {
      blogStore.setViewSiez('big')
    }
    else if (rect.width + 1 > BLOG_MENU_WIDTH) {
      blogStore.setViewSiez('middle')
    }
    else {
      blogStore.setViewSiez('small')
    }
  }
  onBeforeMount(() => {
    window.addEventListener('resize', debounce(resizeHandler, 200))
  })
  onBeforeUnmount(() => {
    window.removeEventListener('resize', debounce(resizeHandler, 200))
  })
}
